/**
 * 办公系统
 * 
 * @author 孙晓晔
 * @version $Id: common.js 1031 2010-03-24 11:32:00Z sunxy $
 */

var tab;

$(function() {
	$("#abc").addClass("ui-state-default ui-corner-all");
	$("#abc").css({ "padding":" .2em", "text-decoration": "none"});

	$("#abc").floatdiv({top:"25px",left:"5px"});	
	
	tabs = $('#tabs').tabs({
		// tabTemplate: '<li><a href="#{href}">#{label}</a> <span class="ui-icon ui-icon-close">Remove Tab</span></li>',
		add: function(event, ui) {
			$(ui.tab).parents('li:first')
	        .append('<span class="ui-tabs-close ui-icon ui-icon-close" title="关闭"></span>')
	        .find('span.ui-tabs-close')
	        .click(function() {
	        	tabs.tabs('remove', $('li', tabs).index($(this).parents('li:first')[0]));
	        });
	    
			tabs.tabs('select', '#' + ui.panel.id);
		}
	});
	
	var flip = 1;
	$("#abc").click(function() {
		flip++;
		$("#CategoryTree").toggle();
		if (flip % 2 == 0) {
			$("#ddd").width(0);
			$("#abc").html("&raquo;");
		} else {
			$("#ddd").width(200);
			$("#abc").html("&laquo;");
		}		

		return false;
	});
	
	$("#dialog_login").dialog( {
		bgiframe : true,
		width : 360,
		height : 165,
		resizable : false,
		draggable : false,
		autoOpen : false
	});
	
	$('#dialog_login').dialog('option', 'title', '景荣办公系统');
	
	var _dialog_option = {
		modal : true,
		autoOpen : false,
		resizeStop : function(event, ui) {
			var width = $(this).dialog('option', 'width');
			var height = $(this).dialog('option', 'height');
			$('#dialog').html(width + "x" + height);
		},

		beforeclose : function(event, ui) {
			$(this).text('');
			$(this).dialog('option', 'height', 'auto');
		},
		
		close : function(event, ui) {
			$(this).dialog('option', 'buttons', {});
		}
	};

	$("#dialog_add").dialog(_dialog_option);
	$("#dialog_edit").dialog(_dialog_option);
	$("#dialog_view").dialog(_dialog_option);
	$("#dialog_emp").dialog(_dialog_option);
	
	$("#placetab").hide();
});

/*
$().ajaxSend(function() {
	$.blockUI({ message: $('#loading') });
});

$().ajaxStart(function() {
	$.blockUI({ message: $('#loading') });
});
*/

function menutree(o) {
	if (o.parentNode) {
		if (o.parentNode.className == "Opened") {
			o.parentNode.className = "Closed";
		} else {
			o.parentNode.className = "Opened";
		}
	}
}
/*
$(document).ajaxStart(function() {	
	$.blockUI({ message: $('#loading'), css: {padding: 5, margin: 5}});
}).ajaxStop($.unblockUI);
*/

$(document).ajaxStop($.unblockUI);

function menu(sURL, sView) {
	$("#placetab").hide();
	$(sView).show();
	// $.blockUI({ message: $('#loading'), css: {padding: 5, margin: 5}});

	sURL = _url(sURL);

	$.get(sURL, function(data) {
		if (data != null && data == '1') {
			$('#dialog_login').dialog('open');
		} else {
			$(sView).html(data);
		}
	});
}

function tab(sURL, sView, tab, title) {
	$("#placeholder").html('');
	// $("#placeholder").hide();
	$(sView).show();
			
	// $.blockUI({ message: $('#loading'), css: {padding: 5, margin: 5}});
	
	$.get(sURL, function(data) {
		if (data != null && data == '1') {
			$('#dialog_login').dialog('open');
		} else {
			var d = 10000 * Math.random();
			// sURL = sPath + "?" + aParams.join("&") + "&rnd=" + Math.ceil(d);
			tab = Math.ceil(d);
			
			var t = 'tabs'+tab;	
			// alert(t);
			tabs.tabs('add', "#"+t, title);
			$("#"+t, "#tabs").load(sURL);
			tabs.tabs('select', "#"+t);
		}
	});
}

function tab22(sURL, sView, tab, title) {
	$("#placeholder").html('');
	// $("#placeholder").hide();
	$(sView).show();
	
	// $.blockUI({ message: $('#loading'), css: {padding: 5, margin: 5}});
			
	$.get(sURL, function(data) {
		if (data != null && data == '1') {
			$('#dialog_login').dialog('open');
		} else {		
			var t = '#tabs'+tab;
			// alert(t);
			if($(t).html() == null ) {
				tabs.tabs('add', t, title);
				$(t, "#tabs").load(sURL);
				tabs.tabs('select', t);
			} else {				
				tabs.tabs('select', t);
			}
		}
	});
}

function dialog_import(url, title) {
	dialog_add(url, title, '600x240');
}

function dialog_add(url, title, xy) {
	dialog_x(url, title, xy, '#dialog_add');
}

function dialog_edit(url, title, xy) {
	dialog_x(url, title, xy, '#dialog_edit');
}

function dialog_view(url, title, xy) {
	dialog_x(url, title, xy, '#dialog_view');
}

function dialog_x(url, title, xy, view) {
	$.get(url, function(data) {
		$(view).html(data);
	});

	var regex = /^(\d+)(x)(\d+)$/;
	if (regex.test(xy)) {
		var cc = xy.split("x");
		var width = parseInt(cc[0]);
		var height = parseInt(cc[1]);
		$(view).dialog('option', 'height', height);
	} else {
		var width = parseInt(xy);
	}

	$(view).dialog('option', 'title', title);
	$(view).dialog('option', 'width', width);
	$(view).dialog('open');
}

var Common = {
	dialog_view_: function (url, title, xy) {
		$('#dialog_view').dialog('option', 'buttons', {

			"关闭": function() { 
				$(this).dialog("close");
			},
			
			"打印": function() { 
				$.jPrintArea("#dialog_view");
				//  $(this).dialog("close");
			}
		});

		dialog_view(url, title, xy);
	},
	
	result: function() {
		var s = $("div[id^='result']:visible");
		
		return "#" + s[0].id;
	}
};

function _error() {	
	$('#dialog_view').dialog('option', 'buttons', {
		"关闭": function() { 
			$(this).dialog("close");
		}		
	});

	var data = "权限受限，请联系管理员！";	

	dialog_view_info(data, '提示信息', '320x160');
}

function dialog_view_info(data, title, xy) {
	if (data == null) {
		data = '权限受限，请联系管理员！';
	}

	if (title == null) {
		title = '提示信息';
	}

	if (xy == null) {
		xy = '320x160';
	}

	$('#dialog_view').html(data);

	var regex = /^(\d+)(x)(\d+)$/;
	if (regex.test(xy)) {
		var cc = xy.split("x");
		var width = parseInt(cc[0]);
		var height = parseInt(cc[1]);
		$('#dialog_view').dialog('option', 'height', height);
	} else {
		var width = parseInt(xy);
	}

	$('#dialog_view').dialog('option', 'title', title);
	$('#dialog_view').dialog('option', 'width', width);
	$('#dialog_view').dialog('open');
}

function view(url, title, xy) {	
	_dialog_view(url, title, xy);
}

function _dialog_view(url, title, xy) {
	$('#dialog_view').dialog('option', 'buttons', { 		
		"关闭": function() { 
			$(this).dialog("close");
		}
	});

	dialog_view(url, title, xy);
}

function emp(id) {
	var url = "emp.php?do=Emp.view&id=" + id;
	$('#dialog_emp').dialog('option', 'buttons', { 		
		"关闭": function() { 
			$(this).dialog("close");
		}
	});

	dialog_x(url, '员工信息', '500x300', '#dialog_emp');
}

function customer(id) {
	var url = "contact.php?do=Customer.view&small=on&id=" + id;
	_dialog_view(url, '客户信息', '600x400');
}

function factory(id) {
	var url = "contact.php?do=Factory.view&small=on&id=" + id;
	_dialog_view(url, '产品工厂', '600x400');
}

function mold(id) {
	var url = "mold.php?do=Mold.view&id=" + id;
	
	_dialog_view(url, '产品信息', '550x320');
}

function material(id) {
	var url = "material.php?do=Material.view&id=" + id + "&bt=1";
	
	_dialog_view(url, '材料信息', '600x360');
}

function car(id) {
	var url = "car.php?do=Car.view&id=" + id;
	
	_dialog_view(url, '车辆信息', '600x360');
}

function machine(id) {
	var url = "info.php?do=Machine.view&id=" + id;
	
	_dialog_view(url, '机器信息', '600x360');
}

function list(url, view) {
	// $.blockUI({ message: $('#loading'), css: {padding: 5, margin: 5}});
	
	if (view == null || view == undefined) {
		var s = $("div[id^='result']:visible");
		view = s[0].id;
	}
	
	$.get(url, function(data) {
		// $('#result').html(data);
		$('#'+view).html(data);
	});
}

function post_find(form, result) {
	if (result == null || result == 'undefined') {
		// result = "result";
		var s = $("div[id^='result']:visible");
				
		result = s[0].id;
	}
	
	// $.blockUI({ message: $('#loading'), css: {padding: 5, margin: 5}});
	
	if (typeof form == 'undefined') {
		var form = document.forms[0];
	}

	var url = _url(form.action);
	var body = _body(form);

	$.post(url, body, function(data) {
		if (data == '1') {
			$('#dialog_login').dialog('open');
		} else {
			
			$('#'+result).html(data);
		}
	});
	
	return false;
}

function find(form, result) {
	post_find(form, result);
}

function _url(sURL) {
	var sPath = sURL.slice(0, sURL.indexOf("?"));
	var sQuery = sURL.slice(sURL.indexOf("?") + 1, sURL.length);

	var aPairs = sQuery.split("&");
	var aParams = new Array();
	for ( var i = 0; i < aPairs.length; i++) {
		var aPair = aPairs[i].split("=");

		var sParam = encodeURIComponent(aPair[0]);
		sParam += "=";
		// sParam += encodeURIComponent(aPair[1]);
		sParam += aPair[1];

		aParams.push(sParam);
	}

	var d = 10000 * Math.random();
	sURL = sPath + "?" + aParams.join("&") + "&rnd=" + Math.ceil(d);

	return sURL;
}

function _body(form) {
	var aParams = new Array();
	var len = form.elements.length;
	for ( var i = 0; i < len; i++) {
		var type = form.elements[i].type;
		if (type == 'button') {
			continue;
		}

		if (type == 'submit') {
			continue;
		}

		if (type == 'reset') {
			continue;
		}

		if (type == 'checkbox'
				&& form.elements[i].checked == false) {
			continue;
		}

		if (type == 'radio'
				&& form.elements[i].checked == false) {
			continue;
		}

		var val = form.elements[i].value;
		if (val != null && val.length > 0) {
			var sParam = encodeURIComponent(form.elements[i].name);
			sParam += "=";
			sParam += encodeURIComponent(val.trim());

			aParams.push(sParam);
		}
	}

	return aParams.join("&");
}

function _param(oForm) {
	var aParams = new Array();
	var sParam;

	for ( var i = 0; i < oForm.elements.length; i++) {
		sParam = oForm.elements[i];
		if (sParam.name.substring(0, 2) == 'c_' && sParam.checked) {
			aParams.push(oForm.elements[i].value);
		}
	}

	return aParams.join(",");
}

function jswin(url, winid, xy) {
	var cc = xy.split("x");
	var width = cc[0];
	var height = cc[1];

	openwin(url, winid, width, height);
}

function openwin(url, winid, w, h) {
	var _left = screen.width / 2 - w / 2;
	var _top = screen.height / 2 - h / 2;

	var newwin = window
			.open(
					url,
					winid,
					"toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,fullscreen=no,copyhistory=no,top="
							+ _top
							+ ",left="
							+ _left
							+ ", width="
							+ w
							+ ",height=" + h);
	newwin.focus();
	return false;
}

function chkbox(form) {
	var len = form.elements.length;
	for ( var i = 0; i < len; i++) {
		var e = form.elements[i];
		if (e.name != 'chkall') {
			e.checked = form.chkall.checked;
		}
	}
}

function expunge(form, result) {
	var count = 0;
	var len = form.elements.length;
	for ( var i = 0; i < len; i++) {
		var e = form.elements[i];
		var name = e.name.substring(0, 2);
		if (name == 'c_' && e.checked) {
			count++;
		}
	}

	if (confirm("您确定删除已选择的" + count + "条记录吗？")) {
		find(form, result);
		return true;
	}

	return false;
}

function fmoney(s, n) {
   n = n > 0 && n <= 20 ? n : 2;
   s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
   var l = s.split(".")[0].split("").reverse();
   var r = s.split(".")[1];
   var t = "";
   for (i = 0; i < l.length; i ++ ) {
      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
   }

   return t.split("").reverse().join("") + "." + r;
}

function query(sQuery) {
	var aPairs = sQuery.split("&");
	var aParams = new Array();
	for ( var i = 0; i < aPairs.length; i++) {
		var aPair = aPairs[i].split("=");
		if (/_s$/.test(aPair[0]) || aPair[0] == 'p') {
			var sParam = encodeURIComponent(aPair[0]);
			sParam += "=";
			sParam += encodeURIComponent(aPair[1]);

			aParams.push(sParam);
		}		
	}

	return "&" + aParams.join("&");
}

function call(number) {
	$('#dialog_add').dialog('option', 'buttons', {

		"关闭": function() {
			$(this).dialog("close");
		},

		"开始拔打": function() {
			if (!confirm("确认是否开始拔打？")) {
				return false;
			}
			
			var form = $("#form_add")[0];

			var body = { };
			body.call = form.call.value;			
			body.number = form.number.value;
			body.exten = form.exten.value;

			$(this).dialog("close");

			$.post('tel.php?do=Call.addPost', body, function(data) {
				alert("正在拔打。。。");
			});
		}
	});

	var url = "tel.php?do=Call.add&number=" + encodeURIComponent(number);
	dialog_add(url, '拔打电话', '450x255');
}

function call2(from, number) {
	$('#dialog_add').dialog('option', 'buttons', {

		"关闭": function() {
			$(this).dialog("close");
		},

		"开始拔打": function() {
			if (!confirm("确认是否开始拔打？")) {
				return false;
			}
			
			var form = $("#form_add")[0];

			var body = { };
			body.call = form.call.value;			
			body.number = form.number.value;
			body.exten = form.exten.value;

			$(this).dialog("close");

			$.post('/t/portal/?do=Call.addPost', body, function(data) {
				alert("正在拔打。。。");
			});
		}
	});

	var url = "/t/portal/?do=Call.add&from=" + encodeURIComponent(from) + "&number=" + encodeURIComponent(number);
	dialog_add(url, '拔打电话', '450x255');
}

function tec(cc) {
	var a = $("table[id^='find_']:visible tr");
	var c = $("table[id^='find_']:visible tr:hidden");
	// alert(c.length);
			
	var b = $("table[id^='find_']:visible tr:last");
	if (c.length == 0) {
		a.hide();
		b.show();
		$(cc).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s");
	} else {
		a.show();
		$(cc).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n");
	}

	return false;
}

function requiredFieldValidator(value) {
	if (value == null || value == undefined || !value.length) {
		return {valid:false, msg:"This is a required field"};
	} else {
		return {valid:true, msg:null};
	}
}

function selectMultipleRows() {
    if (!Slick.GlobalEditorLock.commitCurrentEdit()) { 
    	return; 
    }
    grid.setSelectedRows([0,1,2]);
}

function CurrencySelectCellEditor(args) {
	var $select;
    var defaultValue;
    var scope = this;

    this.init = function() {
        $select = $("<SELECT tabIndex='0' id='currency_'></SELECT>");
        
        $select.empty();
        // alert(currency_json);
        $.each(currency_json, function(k, v) {
        	// alert(k + " = " + v);
        	var item = new Option(v, k);
        	$select[0].options.add(item);
        });
        
        $select.appendTo(args.container);
        
        $select.change(function() {
    		var s = $(this).val();
    		if (s != null && s != '-')　{
    			var url = 'finance.php?do=Finance.ajax_exchange&currency=' + s;
    			$.get(url, function(data) {
    				exchange_item = data; 
    			});
    		 }		
    	});
        
        $select.focus();
    };

    this.destroy = function() {
        $select.remove();
    };

    this.focus = function() {
        $select.focus();
    };

    this.loadValue = function(item) {
    	$select.val(item[args.column.field]);
    	$select.select();
    };

    this.serializeValue = function() {
        return $select.val();
    };

    this.applyValue = function(item,state) {    	
        item[args.column.field] = state;
    };
   
    this.isValueChanged = function() {
        return ($select.val() != defaultValue);
    };

    this.validate = function() {
        return {
            valid: true,
            msg: null
        };
    };

    this.init();
}

function CurrencySelectCellEditor2(args) {
	var $select;
    var defaultValue;
    var scope = this;

    this.init = function() {
        $select = $("<SELECT tabIndex='0' id='currency_'></SELECT>");
        
        $select.empty();
        // alert(currency_json);
        $.each(currency_json, function(k, v) {
        	// alert(k + " = " + v);
        	var item = new Option(v, k);
        	$select[0].options.add(item);
        });
        
        $select.appendTo(args.container);        
        $select.focus();
    };

    this.destroy = function() {
        $select.remove();
    };

    this.focus = function() {
        $select.focus();
    };

    this.loadValue = function(item) {
    	$select.val(item[args.column.field]);
    	$select.select();
    };

    this.serializeValue = function() {
        return $select.val();
    };

    this.applyValue = function(item,state) {    	
        item[args.column.field] = state;
    };
   
    this.isValueChanged = function() {
        return ($select.val() != defaultValue);
    };

    this.validate = function() {
        return {
            valid: true,
            msg: null
        };
    };

    this.init();
}

function MoldCellEditor(args) {
    var $input;
    var defaultValue;
    var scope = this;
    var calendarOpen = false;

    this.init = function() {
        $input = $("<INPUT type=text class='editor-text' />");
        $input.appendTo(args.container);
        $input.focus().select();
        
        $input.autocomplete('mold.php?do=Mold.ajax_code', _mold_option);
        $input.width($input.width() - 18);
    };

    this.destroy = function() {
        $.datepicker.dpDiv.stop(true,true);
        $input.datepicker("hide");
        $input.datepicker("destroy");
        $input.remove();
    };

    this.show = function() {
        if (calendarOpen) {
            $.datepicker.dpDiv.stop(true,true).show();
        }
    };

    this.hide = function() {
        if (calendarOpen) {
            $.datepicker.dpDiv.stop(true,true).hide();
        }
    };

    this.position = function(position) {
        if (!calendarOpen) return;
        $.datepicker.dpDiv
            .css("top", position.top + 30)
            .css("left", position.left);
    };

    this.focus = function() {
        $input.focus();
    };

    this.loadValue = function(item) {
        defaultValue = item[args.column.field];
        $input.val(defaultValue);
        $input[0].defaultValue = defaultValue;
        $input.select();
    };

    this.serializeValue = function() {
        return $input.val();
    };

    this.applyValue = function(item,state) {
        item[args.column.field] = state;
    };

    this.isValueChanged = function() {
        return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function() {
        return {
            valid: true,
            msg: null
        };
    };

    this.init();
}

function fxmul(a, b) {
	return fxmultiply(a, b);
}

function fxmultiply(a, b) {
	if (is_null(a) || is_null(b)) {
		return '';
	}
	
	var f1 = String(a).split(".").length > 1 ? String(a).split(".")[1].length : 0;
	var f2 = String(b).split(".").length > 1 ? String(b).split(".")[1].length : 0;
	var aa = String(a).replace(/^0*|\./g, "");
	var bb = String(b).replace(/^0*|\./g, "");   
	
	return Number(aa) * Number(bb) / Math.pow(10, f1 + f2);
}

function fxadd(a, b) {
	if (is_null(a) && is_null(b)) {
		return 0;
	}
	
	if (is_null(a)) {
		return b;
	}
	
	if (is_null(b)) {
		return a;
	}
	
	var f1 = String(a).split(".").length > 1 ? String(a).split(".")[1].length : 0;
	var f2 = String(b).split(".").length > 1 ? String(b).split(".")[1].length : 0;
	var m = Math.pow(10, Math.max(f1, f2));
	
	return (a*m + b*m) / m;
}

function is_null(s) {
	if (s == null || s == 'undefined') {
		return true;
	}
	
	if (s == '') {
		return true;
	}
	
	return false;
}

String.prototype.format = function() {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g, function(m, i) {
    	return args[i];
    });
};

function current_date() {
	var d = new Date();
	var y = d.getFullYear();
	var m = d.getMonth() + 1;
	var d = d.getDate();
	
	var mm = m < 10 ? "0" + m : m;
	var dd = d < 10 ? "0" + d : d;
	
	var ret = y + "-" + mm + "-" + dd;
	// alert(ret);
	
	return ret;
}
